#include "SDLSprite.h"

SDLSprite::SDLSprite()
	: SDLComponent()
	, x(0), y(0)
	, surface(0)
	, destination(0)
{
}
SDLSprite::SDLSprite( std::string filePath, int x, int y, SDL_Surface* destination )
	: SDLComponent()
	, x(x), y(y)
	, destination(destination) 
{
	surface = LoadImage( filePath );
	isVisible = true;
}

SDLSprite::~SDLSprite()
{
}

void SDLSprite::SetSprite( std::string filePath, int x, int y, SDL_Surface* destination )
{
	SDL_FreeSurface(surface);
	surface = LoadImage( filePath );
	this->x = x;
	this->y = y;
	this->destination = destination;
	isVisible = true;
}
void SDLSprite::Update()
{}
void SDLSprite::Draw()
{
	if(isVisible)
	{
		ApplyImage( x, y, surface, destination );
	}
}
void SDLSprite::Reset()
{
	SDL_FreeSurface( surface );
}
SDL_Surface* SDLSprite::LoadImage( std::string filepath )
{
	SDL_Surface* loadedImage = NULL;
	SDL_Surface* optimizedImage = NULL;
	loadedImage = SDL_LoadBMP( filepath.c_str() );
	if( loadedImage != NULL )
	{
		optimizedImage = SDL_DisplayFormat( loadedImage );
		if(optimizedImage != NULL)
		{
			Uint32 colorKey = SDL_MapRGB( optimizedImage->format, 0xFF, 0, 0xFF );
			SDL_SetColorKey( optimizedImage, SDL_SRCCOLORKEY, colorKey);
		}
		SDL_FreeSurface( loadedImage );
		return optimizedImage;
	}
}
void SDLSprite::ApplyImage( int x, int y, SDL_Surface* source, SDL_Surface* destination )
{
	SDL_Rect offset;
	offset.x = x;
	offset.y = y;
	SDL_BlitSurface(source, NULL, destination, &offset);
}
void SDLSprite::SetPosition(int x, int y)
{
	this->x = x;
	this->y = y;
}